
package dom;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class newMain {

    public static void main(String[] args) {
        try {
          //DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            //tao doi tuong builder
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            //Document doc bang su dung builder doc file shiporder.xml
            Document doc = builder.parse(new File("shiporder.xml"));
            //Dung doi tuong Node de getElement by Tag
            NodeList titleNodes = doc.getElementsByTagName("title");
            //In ra so Node minh da get
            System.out.println("Count :" + titleNodes.getLength());
            //For theo danh sach Node title roi UpperCase
            for (int i = 0; i < titleNodes.getLength(); i++) {
                String title = titleNodes.item(i).getTextContent();
                titleNodes.item(i).setTextContent(title.toUpperCase());
            }

            //Tao dooi tuong Node moi tuong ung la Item
            Node newItem = doc.createElement("item");
            //Tao dooi tuong Node moi tuong ung la Title
            Node newTitle = doc.createElement("title");
            //Set them noi dung cho Node vua tao la Teo
            newTitle.setTextContent("Teo");
            //New Item chap nhan them Node con
            newItem.appendChild(newTitle);

            doc.getDocumentElement().appendChild(newItem);
            //Tao doi tuong source chuan bi ghi file
            Source source = new DOMSource(doc);
            //Su dung doi tuong transformer(nguoi van chuyen)
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            //Reslt la ket qua ghi file"ten file"
            Result result = new StreamResult(new File("other-shiporder.xml"));
            //Doi tuong transformer thuc thi task bao gom source va result
            transformer.transform(source, result);
            System.out.println("OK");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
